package com.openlogic.common.logic.aspect;

import org.noear.solon.core.handle.Action;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

import com.openlogic.common.logic.annotation.RuleLog;
import com.openlogic.common.logic.constants.RuleTypeConstants;
import com.openlogic.common.logic.log.factory.RecordLogFactory;
import com.openlogic.common.logic.log.strategy.RecordDecisionLogStrategy;

import cn.hutool.core.util.ObjectUtil;

/**
* @ClassName: RuleLogAspect
* @Description: 规则操作日志记录处理
* @author weiyongpeng
* @date 2024年9月10日 上午8:29:05
 */
public class RuleLogAspect implements Filter {
	
	/**
	 * 请求开始时间
	 */
	ThreadLocal<Long> startTime = new ThreadLocal<>();
	
	@Override
	public void doFilter(Context ctx, FilterChain chain) throws Throwable {
		System.out.println("开始过滤...");
		// 开始时间
		startTime.set(System.currentTimeMillis());
		chain.doFilter(ctx);
		Action action = ctx.action();
		// 获取函数上的注解
		RuleLog ruleLog = action.method().getAnnotation(RuleLog.class);

		if (ruleLog != null) {
			// 获取决策类型
			RuleTypeConstants ruleType = ruleLog.ruleType();
			if (ObjectUtil.isNull(ctx.errors)) { // 成功
				Object jsonResult = ctx.result;
				RecordDecisionLogStrategy logStrategy = RecordLogFactory.getInvokeStrategyMap(ruleType.getCode());
				logStrategy.handleLog(ctx, ruleLog, null, jsonResult, startTime);
			} else { // 失败
				Throwable e = ctx.errors;
				RecordDecisionLogStrategy logStrategy = RecordLogFactory.getInvokeStrategyMap(ruleType.getCode());
				logStrategy.handleLog(ctx, ruleLog, e, null, startTime);
			}
		}
	}
}
